package org.epidroid.epidroid.androsoul.engine.contacts;

import java.net.URLDecoder;

import org.epidroid.epidroid.androsoul.engine.utils.Visitor;

public class Location {

	public static final String LOGCAT = "epidroid";

	private String _ip;
	private String _location;
	private String _privateloc;

	public Location(String ip, String privateloc) {
		this._ip = ip;
		this._location = ip2Location();
		this._privateloc = URLDecoder.decode(privateloc);
	}

	/**
	 * Check if an ip adress matches a prefix
	 * 
	 * @param digits
	 *            ip adress
	 * @param prefix
	 *            prefix to be matched
	 * @return true if matched
	 */
	private boolean checkPrefix(String[] digits, String prefix) {
		String[] pdigits = prefix.split("\\.");
		if (pdigits.length > digits.length)
			return false;

		for (int i = 0; i < pdigits.length; i++) {
			if (!pdigits[i].equals(digits[i]))
				return false;
		}

		return true;
	}

	/**
	 * @return Textual location corresponding to an ip adress.
	 */
	private String ip2Location() {
		String[] dig = this._ip.split("\\.");
		if (dig.length < 4)
			return "";

		if (checkPrefix(dig, "10.120"))
			return "SM " + dig[2] + " #" + dig[3];
		if (checkPrefix(dig, "10.247"))
			return "Pasteur" + " #" + dig[3];
		if (checkPrefix(dig, "10.248"))
			return "SR Lab" + " #" + dig[3];
		if (checkPrefix(dig, "10.249"))
			return "Mid Lab" + " #" + dig[3];
		if (checkPrefix(dig, "10.250"))
			return "Cisco Lab" + " #" + dig[3];
		if (checkPrefix(dig, "10.244"))
			return "Villejuif";

		return "";
	}

	/**
	 * @return the best describing location for the contact. If the ip adress'
	 *         location is known, return this location. Otherwise, return the
	 *         location described by the user in its status.
	 */
	public String getBestLocation() {
		if (!this._location.equals(""))
			return this._location;
		else if (this._privateloc.equals(""))
			return "Unknown location";
		else
			return this._privateloc;
	}

	public void accept(Visitor v) {
		v.visit(this);
	}

	// / Getters
	public String getIp() {
		return _ip;
	}

	public String getLocation() {
		return _location;
	}
}
